<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/05/14
 */
namespace common\logic;

use Codeception\Lib\Connector\Guzzle;
use common\models\Booker;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use yii;

class DiveBooker {
    const HOST = 'https://divebooker.com';
    const API = [
        'order' => '/apiv1/liveaboards/id/%d/order',
        'token' => '/apiv1/token',
    ];

    public static function makeOrder($tripId, $occupancyId, $occupancyQuantity, $enName) {
        $c = new Client();
        $trip = Trip::getOneTrip($tripId);
        $bookerBoatId = Booker::dive2booker($trip['boat_id'], Booker::TYPE_BOAT);
        $bookerTripId = Booker::dive2booker($tripId, Booker::TYPE_TRIP);
        $bookerTourId = Booker::dive2booker($trip['tour_id'], Booker::TYPE_TOUR);
        $bookerOccupancyId = Booker::dive2booker($occupancyId, Booker::TYPE_OCCUPANCY);
        $query = [
            'token' => self::getToken(),
            'tripid' => $bookerTripId,
            'occupancyid' => $bookerOccupancyId,
            'occupancyquantity' => $occupancyQuantity,
            //'productid' => $bookerTourId,//这里貌似是 设备id
            //booker的product可能是tour 也可能是另一类可卖的东西,这个参数待定
            //'productquantity' => 2,
            //'userdata' => 'title|firstName|lastName|email|phone|specialRequests',
            'userdata' => 'Cooldive-client|' . $enName[0] . '|' . $enName[1] . '|booking@cooldive.com.cn||',
        ];
        try {
            $response = $c->request('GET', self::HOST . sprintf(self::API['order'], $bookerBoatId), [
                'query' => $query,
                //'debug' => true,
                'timeout' => 5,
            ]);
        } catch (\Exception $e) {
            Yii::error($e, __METHOD__);
            return ['err'=>1,'msg'=>$e->getMessage()];
        }
        $r = json_decode($response->getBody(), true);
        Yii::info($r, __METHOD__);
        if ($r['status'] == 1) {
            return [
                'err' => 0,
                'bookerOrderId' => $r['results']['id']
            ];
        } else {
            Yii::error([
                    'tripId' => $tripId,
                    'occupancyId' => $occupancyId,
                    'occupancyQuantity' => $occupancyQuantity,
                    'boatId' => $bookerBoatId
                ] + $query, __METHOD__);
            return [
                'err' => 2,
                'msg' => $r['message']
            ];
        }
    }

    public static function getToken() {
        return file_get_contents(Yii::$app->params['env']['DATA_PATH'] . 'dive-booker-token.txt');
    }

    public static function updateToken() {
        $res = (new Client())->request('GET', self::HOST . self::API['token'] . '?authkey=freefishdive&secret=65eb72c92a54');
        $r = json_decode($res->getBody(), true);
        if (empty($r['status']) || $r['status'] != 1) {
            Yii::error(var_export($res->getBody(), true), __METHOD__);
            exit;
        }
        $token = $r['results']['token']['value'];
        file_put_contents(Yii::$app->params['env']['DATA_PATH'] . 'dive-booker-token.txt', $token);
    }
}
